// pages/signature/signature.js
// pages/autWay/identity.js
const app = getApp()
import {
  urls
} from '../../api/urls'
import Toast from '../../dist/toast/toast';
import {
  signature_send
} from '../../api/request'
// import Toast from '../../dist/toast/toast';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    fileList: [],
    identity_room_code: '', //门牌号
    identity_Url: '', //身份证照片上传地址
    identity_name: '', //身份证姓名
    identity_mobile: '', //联系方式

    identity_id: '', //证号
    identity_addr: '', //身份证地址，
    identity_gender: '', //性别
    identity_nationality: '', //民族
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {},


  //  Procedure signature_send(m_openid in varchar,
  //    m_property_code in varchar,
  //    m_name in varchar,
  //    m_signature_url in varchar,
  //    ret             out t_cursor) as


  //业主签名发起实名认证登记
  signature_send() {
    let that = this
    console.log('-----identity_url=' + that.data.identity_url)
    var data = {
      para: [app.globalData.cur_my_openid,
        app.globalData.cur_property_code,
        that.data.identity_name,
        that.data.identity_url,
      ]
    }

    console.log('-----data=', data)

    signature_send(data).then(res => {
      console.log('----signature_send------', res)
      if (res.data[0].ERRORCODE == '1') {
        console.log('实名认证登记成功', res.data[0].ROOM_CODE)
        that.setData({
          identity_room_code: res.data[0].PROPERTY_NAME + '(' + res.data[0].ROOM_CODE + ')',
          identity_mobile: res.data[0].MOBILE
        })

        wx.setStorageSync('certification_status', true)
        //更新全局变量
        app.globalData.phoneNumber = res.data[0].MOBILE
        app.globalData.cur_room_code = res.data[0].ROOM_CODE
        app.globalData.cur_my_name = res.data[0].ROOM_NAME
        app.globalData.cur_property_code = res.data[0].PROPERTY_CODE
        app.globalData.cur_property_name = res.data[0].PROPERTY_NAME
        app.globalData.cur_street_name = res.data[0].STREET_NAME
        wx.setStorageSync('openid', app.globalData.cur_my_openid)

        wx.showModal({
          title: '业主签名发起',
          confirmText: "确定",
          showCancel: false,
          content: '你同意成立业主委员会的签名材料已提交本小区业主委员会（筹备组）',
        })

        Toast.success('【' + that.data.identity_name + '】的签名提交成功');

      } else {
        console.log('-----业主签名发起失败------')
        wx.showModal({
          title: '业主签名发起失败',
          confirmText: "确定",
          showCancel: false,
          content: '你提交的证件在小区业主数据库中没有查询到，请检查身份证或不动产证，向致电业主委员会（筹备组）查询业主信息',
        })

      }
    })
  },

  back_home() {
    wx.navigateBack({

    })
  },


  //身份证
  shenfenzheng() {
    this.photo("shenfenzheng")
  },

  //拍照或者从相册选择要识别的照片
  photo(type) {
    let that = this
    var typess = ''

    wx.showActionSheet({
      itemList: ['从手机相册选择', '拍照'],
      success: function(res) {
        console.log(res.tapIndex)
        if (res.tapIndex == '0') typess = 'album'
        if (res.tapIndex == '1') typess = 'camera'
        wx.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'],
          sourceType: [typess],
          success(res) {
            // tempFilePath可以作为img标签的src属性显示图片
            let imgUrl = res.tempFilePaths[0];
            that.uploadImg(type, imgUrl)
            wx.showLoading({
              title: '上传中...'
            })
          }
        })
      },
      fail: function(res) {
        console.log(res.errMsg)
      }
    })
  },

  // 上传图片到云存储
  uploadImg(type, imgUrl) {
    let that = this
    wx.cloud.uploadFile({
      cloudPath: 'ocr/' + type + '.png',
      filePath: imgUrl, // 文件路径
      success: res => {
        console.log("上传成功！", res.fileID)
        that.getImgUrl(type, res.fileID)
        wx.hideLoading()
      },
      fail: err => {
        console.log("上传失败", err)
      }
    })
  },

  //获取云存储里的图片url
  getImgUrl(type, imgUrl) {
    let that = this
    wx.cloud.getTempFileURL({
      fileList: [imgUrl],
      success: res => {
        let imgUrl = res.fileList[0].tempFileURL
        console.log("获取图片url成功", imgUrl)
        that.setData({
          identity_url: imgUrl
        })
        that.shibie(type, imgUrl)
        wx.showLoading({
          title: '认证中...'
        })
      },
      fail: err => {
        console.log("获取图片url失败", err)
      }
    })
  },

  //调用云函数，实现OCR识别
  shibie(type, imgUrl) {
    let that = this
    wx.cloud.callFunction({
      name: "orc",
      data: {
        type: type,
        imgUrl: imgUrl
      },
      success(res) {
        console.log("证件识别成功！", res)
        wx.hideLoading()

        that.setData({
          identity_name: res.result.name,
          identity_id: res.result.id,
          identity_addr: res.result.addr,
          identity_gender: res.result.gender,
          identity_nationality: res.result.nationality,

          /*
          addr: "重庆市江北区洋河中路35号2幢6-6"
          errCode: 0
          errMsg: "openapi.ocr.idcard:ok"
          gender: "男"
          id: "510215196809050479"
          name: "陈怀俊"
          nationality: "汉"
          type: "Front"
          */

        })
        that.signature_send();
      },

      fail(res) {
        wx.hideLoading()
        Toast.fail('识别失败');
      },

    })
  }

})